package online.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Auther: 狼芒
 * @Date: 2021/9/2 0:21
 * @Descrintion: 文件相关测试类
 * @version: 1.0
 */
@Slf4j
@Controller
public class FlieController {

    @ResponseBody
    @PostMapping("/updateFile")
    public String updateFile(@RequestParam("name") String name,
                             @RequestPart("headerImg") MultipartFile headerImg,
                             @RequestPart("photo") MultipartFile[] photos) throws IOException {
        log.error("上传的信息: name= {}, headerImg = {}, photos = {}", name, headerImg, photos);

        //文件为空返回错误信息
        if (headerImg.isEmpty() || photos.length < 1) {
            return "上传文件不能为空";
        }
        StringBuilder stringBuilder = new StringBuilder();
        String headerImgName = headerImg.getOriginalFilename();
        headerImg.transferTo(new File("F:\\temporaryFile\\" + headerImgName));
        stringBuilder.append("headerImgName:").append(headerImgName)
                .append("size:").append(headerImg.getSize());
        for (int i = 0; i < photos.length; i++) {
            if (!photos[i].isEmpty()){
                photos[i].transferTo(new File("F:\\temporaryFile\\" + photos[i].getOriginalFilename()));
                stringBuilder.append("\n文件名：").append(photos[i].getOriginalFilename()).append("大小：").append(photos[i].getSize());
            }
        }
        return stringBuilder.toString();
    }
}
